import React, { useState } from 'react';
import { Box, Typography, IconButton } from '@mui/material';
import { styled } from '@mui/material/styles';
import TreeItem from '@mui/lab/TreeItem';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import { ChromePicker, ColorResult } from 'react-color';
import { useDispatch } from 'react-redux';
import { changeInstanceColor } from '../../redux/slices/generalSlice';
import { experimentLabelColor, bgDarker, bgLight, radius } from '../../theme';
import { RandomColorLensIcon, SquareIcon } from './NetPyNEIcons';

const StyledTreeItem = styled(TreeItem)(({ theme }) => ({
  '& .MuiTreeItem-iconContainer': {
    marginRight: '5px',
  },
  '& .MuiTreeItem-label': {
    paddingTop: '2px',
    paddingBottom: '2px',
    paddingRight: '8px',
    borderRadius: radius,
    '&:hover': {
      backgroundColor: '#333333',
    },
  },
}));

const StyledLeafTreeItem = styled(TreeItem)(() => ({
  '& .MuiTreeItem-iconContainer': {
    width: 0,
  },
}));

const ControlsContainer = styled(Box)(() => ({
  '& .MuiIconButton-root': {
    padding: '0 !important',
    marginLeft: '0.5rem',
    color: experimentLabelColor,
    '&:hover': {
      color: 'white',
    },
  },
}));

const ColorPickerContainer = styled(Box)(() => ({
  position: 'absolute',
  top: '1.6rem',
  right: '0',
  height: '3rem',
}));

const ColorPickerBox = styled(Box)(() => ({
  position: 'absolute',
  zIndex: 1000,
  right: '0',
  backgroundColor: `${bgDarker} !important`,
  padding: '0.2rem',
  '& label': {
    color: '#ffffff !important',
    fontFamily: 'Roboto, arial',
    fontSize: '11px',
    fontWeight: 400,
  },
  '& input': {
    backgroundColor: `${bgLight} !important`,
    color: '#ffffff !important',
    boxShadow: 'none !important',
    fontFamily: 'Roboto, arial',
    fontSize: '11px',
    fontWeight: 400,
  },
  '& svg': {
    fill: '#ffffff !important',
  },
  '& svg:hover': {
    background: 'transparent !important',
  },
  '& .hue-horizontal': {
    borderRadius: '10px',
  },
}));

interface ControlPanelTreeItemProps {
  nodeId: string;
  label: string;
  type: string;
  onNodeSelect: (nodeId: string) => void;
  onVisibilityClick: (event: React.MouseEvent, nodeId: string) => void;
  disableRandom?: boolean;
  children?: React.ReactNode;
  [key: string]: any;
}

/**
 * ControlPanelTreeItem Component
 * Tree item for experiment control panel
 */
const ControlPanelTreeItem: React.FC<ControlPanelTreeItemProps> = ({
  nodeId,
  label,
  type,
  onNodeSelect,
  onVisibilityClick,
  disableRandom = false,
  children,
  ...otherProps
}) => {
  const dispatch = useDispatch();
  const [colorPickerOpen, setColorPickerOpen] = useState(false);
  const [visible, setVisible] = useState(true);

  const handleColorChange = (color: ColorResult): void => {
    const colorObj = {
      r: color.rgb.r ?? 0,
      g: color.rgb.g ?? 0,
      b: color.rgb.b ?? 0,
      a: color.rgb.a ?? 1,
    };
    dispatch(changeInstanceColor({ instancePath: nodeId, color: colorObj }));
  };

  const handleRandomColor = (): void => {
    const randomColor = {
      r: Math.floor(Math.random() * 255),
      g: Math.floor(Math.random() * 255),
      b: Math.floor(Math.random() * 255),
      a: 1,
    };
    dispatch(changeInstanceColor({ instancePath: nodeId, color: randomColor }));
  };

  const TreeItemComponent = children ? StyledTreeItem : StyledLeafTreeItem;

  return (
    <TreeItemComponent
      nodeId={nodeId}
      label={
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            width: '100%',
          }}
        >
          <Typography
            variant="body2"
            onClick={() => onNodeSelect(nodeId)}
            sx={{ cursor: 'pointer', flex: 1 }}
          >
            {label}
          </Typography>
          <ControlsContainer>
            {!disableRandom && (
              <IconButton size="small" onClick={handleRandomColor}>
                <RandomColorLensIcon />
              </IconButton>
            )}
            <IconButton
              size="small"
              onClick={(e) => {
                setVisible(!visible);
                onVisibilityClick(e, nodeId);
              }}
            >
              {visible ? <VisibilityIcon /> : <VisibilityOffIcon />}
            </IconButton>
            <Box sx={{ position: 'relative' }}>
              <IconButton
                size="small"
                onClick={() => setColorPickerOpen(!colorPickerOpen)}
              >
                <SquareIcon />
              </IconButton>
              {colorPickerOpen && (
                <ColorPickerBox>
                  <ChromePicker
                    color={{ r: 255, g: 255, b: 255, a: 1 }}
                    onChange={handleColorChange}
                  />
                </ColorPickerBox>
              )}
            </Box>
          </ControlsContainer>
        </Box>
      }
      {...otherProps}
    >
      {children}
    </TreeItemComponent>
  );
};

export default ControlPanelTreeItem;

